package com.backwaveweibo.bww.service;

import com.backwaveweibo.bww.cache.ApplicationContextHolder;
import com.backwaveweibo.bww.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 点赞功能服务
 */
@Service
@Transactional
@Slf4j
public class LikeService {
    //喜欢这个微博的用户集合
    private static final String LIKE_WEIBO = "WEIBO_%s:LIKE_USER";
    //不喜欢这个微博的用户集合
    private static final String DISLIKE_WEIBO = "WEIBO_%s:DISLIKE_USER";

    @Resource
    RedisUtil redisUtil;




    private RedisUtil getRedisUtil(){

        if (redisUtil == null){
            redisUtil = ApplicationContextHolder.getBean("redisUtil");
        }
        log.info("更换redis数据库");
        redisUtil.changeDb(0);
        return redisUtil;
    }
    public Boolean isLike(Long weiboId,Long userId){
        redisUtil = getRedisUtil();
        String isLike = String.format(LIKE_WEIBO, weiboId);
        boolean b = redisUtil.sHasKey(isLike, userId);
        return b;
    }
    public Boolean isDislike(Long weiboId,Long userId){
        redisUtil = getRedisUtil();
        String isDislike = String.format(DISLIKE_WEIBO, weiboId);
        boolean b = redisUtil.sHasKey(isDislike, userId);
        return b;
    }

    public Boolean likeWeibo(Long weiboId,Long userId){
        redisUtil = getRedisUtil();
        String likeWeibo = String.format(LIKE_WEIBO, weiboId);
        long result = redisUtil.sSet(likeWeibo, userId);
        return result==1;
    }
    public Boolean disLikeWeibo(Long weiboId,Long userId){
        redisUtil = getRedisUtil();
        String dislikeWeibo = String.format(DISLIKE_WEIBO,weiboId);
        long result = redisUtil.sSet(dislikeWeibo, userId);
        return result==1;
    }
    public Long getLikeCount(Long weiboId){
        String likeWeiboCountKey = String.format(LIKE_WEIBO, weiboId);
        long result = redisUtil.sGetSetSize(likeWeiboCountKey);
        return result;
    }
    public Long getDislikeWeiboCount(Long weiboId){
        String disWeiboKey = String.format(DISLIKE_WEIBO, weiboId);
        long result = redisUtil.sGetSetSize(disWeiboKey);
        return result;
    }
}
